var express = require('express');
var router = express.Router();

/* GET users listing. */
router.post('/',isLogin);
router.get('/', function(req, res, next) {
  res.render("users/login",{
    title:"用户登录",
    msg:req.flash('msg').toString()
  });
});

/* post users login. */
//router.post('/login',isLogin);
router.post('/login', function(req, res, next) {
  if((req.body.username!=="admin" && req.body.pw!=="123456") || (req.body.username!=="guest" && req.body.pw!=="123456")){
    req.flash('msg', '用户名密码错!');
    return res.redirect("/users");
  }
  req.session.username = req.body.username;
  req.flash('msg', '登录成功!');


  return res.redirect("/users/profiles")
});
/*用户中心*/
router.get('/profiles', notLogin);
router.get('/profiles', function(req, res, next) {
  res.render("users/profiles",{
    title:"欢迎您回来",
    user:req.session.username,
    sid:req.session.id,
    msg:req.flash('msg').toString()
  })
});

/*用户中心*/
//router.get('/chat', notLogin);
router.get('/chat', function(req, res, next) {
  res.render("chat/single",{
    title:"聊天室",
    user:req.session.username,
    msg:req.flash('msg').toString()
  })
});

/*退出*/
router.get('/logout', notLogin);
router.get('/logout', function(req, res, next) {
  if(1==req.query.type){
    req.session.username="";
    req.flash('msg',"您己被其它用户挤下来了！");
  }else{
    req.session.username="";
    req.flash('msg',"您己成功退出");
  }
  return res.redirect("/users");
});

/**
 * 判断是否登录
 */
//未登录
function notLogin(req,res,next){
  if(!req.session.username){
    req.flash("msg","您好,请您先登录");
    return res.redirect("/users");
  }
  next();
};
//己登录
function isLogin(req,res,next){
  if(req.session.username){
    req.flash("msg","您己登录，请先退出");
    return res.redirect("back");
  }
  next();
}

module.exports = router;
